<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        .container {
            height: 180px;
            width: 180px;
        }

        .move {
            height: 100px;
            width: 100px;
            background-color: lightcoral;
            transition: 1s;
        }

        .show {
            transform: translate(100px, 100px);
            opacity: 1;
        }

        .hide {
            opacity: 0;
            transform: translate(0, 0);
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="move"></div>
    </div>
    <button onclick="toggle()">Click</button>

    <script type="text/javascript">
        let isHide = true;
        const el = document.querySelector('.move');

        function toggle() {
            isHide = !isHide;

            // 如果`isHide` 说明要隐藏了 监听动画结束后隐藏元素 再取消事件
            // 如果`!isHide` 说明要从隐藏状态切换回来
            if (isHide) {
                el.addEventListener('transitionend', () => {
                    el.style.display = 'none';
                }, { 'once': true });

                el.className = 'move hide';
            }
            else {
                el.style.display = 'block';

                // 切换隐藏状态后 立刻触发一次回流`reflow` 可以固定住元素位置
                // 然后再设置样式 就能做到动画效果
                el.getBoundingClientRect();
                el.className = 'move show';
            }
        }
    </script>
</body>

</html>